package models

import (
	"time"

	"github.com/beego/beego/v2/client/orm"
)

// MiniprogramContent 小程序内容模型
type MiniprogramContent struct {
	BaseModel
	Title       string `orm:"size(100)" json:"title"`
	Type        string `orm:"size(20)" json:"type"` // article:文章, notice:公告, help:帮助
	CoverImage  string `orm:"size(255)" json:"cover_image"`
	Summary     string `orm:"size(500)" json:"summary"`
	Content     string `orm:"type(text)" json:"content"`
	Author      string `orm:"size(50)" json:"author"`
	Status      int8   `orm:"default(1)" json:"status"`       // 1:显示, 0:隐藏
	SortOrder   int    `orm:"default(0)" json:"sort_order"`   // 排序
	ViewCount   int    `orm:"default(0)" json:"view_count"`   // 浏览次数
	IsTop       int8   `orm:"default(0)" json:"is_top"`       // 1:置顶, 0:不置顶
	PublishTime int64  `orm:"default(0)" json:"publish_time"` // 发布时间
}

// TableName 设置表名
func (m *MiniprogramContent) TableName() string {
	return "ss_miniprogram_content"
}

// GetContentById 根据ID获取内容
func GetContentById(id int64) (*MiniprogramContent, error) {
	content := &MiniprogramContent{BaseModel: BaseModel{Id: id}}
	o := orm.NewOrm()
	err := o.Read(content)
	return content, err
}

// GetContentList 获取内容列表
func GetContentList(page, pageSize int, filters map[string]interface{}) ([]*MiniprogramContent, int64, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(MiniprogramContent))

	// 应用过滤条件
	if title, ok := filters["title"].(string); ok && title != "" {
		qs = qs.Filter("title__contains", title)
	}

	if contentType, ok := filters["type"].(string); ok && contentType != "" {
		qs = qs.Filter("type", contentType)
	}

	if status, ok := filters["status"].(int8); ok {
		qs = qs.Filter("status", status)
	}

	// 排除已删除的记录
	qs = qs.Filter("is_deleted", 0)

	// 获取总数
	total, _ := qs.Count()

	// 分页查询
	var contents []*MiniprogramContent
	_, err := qs.OrderBy("-is_top", "sort_order", "-id").Limit(pageSize, (page-1)*pageSize).All(&contents)

	return contents, total, err
}

// CreateContent 创建内容
func CreateContent(content *MiniprogramContent) (int64, error) {
	// 如果没有设置发布时间，则使用当前时间
	if content.PublishTime == 0 {
		content.PublishTime = time.Now().Unix()
	}

	o := orm.NewOrm()
	id, err := o.Insert(content)
	return id, err
}

// UpdateContent 更新内容
func UpdateContent(content *MiniprogramContent) error {
	o := orm.NewOrm()
	_, err := o.Update(content)
	return err
}

// DeleteContent 删除内容（软删除）
func DeleteContent(id int64) error {
	o := orm.NewOrm()
	content := &MiniprogramContent{BaseModel: BaseModel{Id: id}}
	if err := o.Read(content); err != nil {
		return err
	}

	content.IsDeleted = 1
	_, err := o.Update(content, "IsDeleted")
	return err
}

// GetActiveContents 获取当前有效的内容列表
func GetActiveContents(contentType string, limit int) ([]*MiniprogramContent, error) {
	o := orm.NewOrm()
	var contents []*MiniprogramContent
	qs := o.QueryTable(new(MiniprogramContent)).Filter("status", 1).Filter("is_deleted", 0)

	if contentType != "" {
		qs = qs.Filter("type", contentType)
	}

	_, err := qs.OrderBy("-is_top", "sort_order", "-publish_time").Limit(limit).All(&contents)
	return contents, err
}
